<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-planStartDate>
                <el-date-picker
                  v-model="formInfo.data.planStartDate"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="dateTimePickerOptions.disabledDate"
                  placeholder="请选择计划开始日期"
                />
              </template>
              <template v-slot:form-planFinishDate>
                <el-date-picker
                  v-model="formInfo.data.planFinishDate"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="dateTimePickerOptions.disabledDate"
                  placeholder="请选择计划结束日期"
                />
              </template>
              <template v-slot:form-patrolRouteName>
                <el-input
                  v-model="formInfo.data.patrolRouteName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择巡检路线"
                >
                  <template #append>
                    <el-icon @click="_selectPatrolRoute"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-execResponseUserName>
                <el-input
                  v-model="formInfo.data.execResponseUserName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择执行负责人"
                >
                  <template #append>
                    <el-icon @click="selectExecResponseUser"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-execCoordinationUserName>
                <el-input
                  v-model="formInfo.data.execCoordinationUserName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择执行协同人"
                >
                  <template #append>
                    <el-icon @click="selectExecCoordinationUser"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-remindDuration>
                <div class="flex">
                  <el-input-number
                    v-model="formInfo.data.remindDuration"
                    style="width: 65%"
                    controls-position="right"
                    :min="0"
                    :max="999999999999999999"
                    :precision="1"
                    placeholder="请输入内容"
                    class="flex-input"
                  >
                  </el-input-number>
                  <select-model
                    v-model="formInfo.data.remindTimeType"
                    type-code="remind_time_type"
                    :check-default="false"
                    :clearable="false"
                    style="width: 35%"
                    class="flex-select"
                  />
                </div>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
      <select-patrol-route
        v-if="selectPatrolRouteInfo.visible"
        v-model:show-dialog="selectPatrolRouteInfo.visible"
        :exclude-query-list="selectPatrolRouteInfo.excludeQueryList"
        :query="selectPatrolRouteInfo.query"
        :check-box="false"
        :highlight-row="true"
        @callback="selectPatrolRouteCallBack"
      />
      <SelectUsers
        v-if="execResponseUserInfo.visible"
        v-model:show-dialog="execResponseUserInfo.visible"
        :query="execResponseUserInfo.query"
        :api="execResponseUserInfo.api"
        :check-box="false"
        :highlight-row="true"
        @callback="selectExecResponseUserBack"
      />
      <SelectUsers
        v-if="execCoordinationUserInfo.visible"
        v-model:show-dialog="execCoordinationUserInfo.visible"
        :query="execCoordinationUserInfo.query"
        :api="execCoordinationUserInfo.api"
        :check-box="true"
        :save-empty="true"
        :highlight-row="false"
        :checked-row-list="execCoordinationUserInfo.checkedRowList"
        @callback="selectExecCoordinationUserBack"
      />
    </div>
  </div>
</template>

<script setup nmae="BrandModify">
import PageForm from '@/components/PageForm/index'

import selectPatrolRoute from '@/components/SelectPatrolRoute/index'
import SelectUsers from '@/components/SelectUsers/index'
import { getDeptUserAll, getRrgUserList } from '@/api/base'
import { creatTask, updateTask, getTaskById } from '@/api/patrol.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id', 'title'])

const dateTimePickerOptions = ref({})
let validateRemind = (rule, value, callback) => {
  let num = formInfo.data.remindDuration
  if (formInfo.data.remindTimeType == '1') {
    if (num < 5) {
      callback(new Error('输入的提醒分钟必须大于等于5！'))
    } else {
      callback()
    }
  } else if (
    formInfo.data.remindTimeType == '2' ||
    formInfo.data.remindTimeType == '3'
  ) {
    if (num <= 0) {
      callback(new Error('输入的提醒小时或天必须大于0！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const formInfo = reactive({
  ref: null,
  data: {
    remindTimeType: '1',
  },
  fieldList: [
    {
      label: '巡检路线',
      value: 'patrolRouteName',
      type: 'slot',
    },
    {
      label: '计划开始时间',
      value: 'planStartDate',
      type: 'slot',
    },
    {
      label: '计划结束时间',
      value: 'planFinishDate',
      type: 'slot',
    },
    {
      label: '执行负责人',
      value: 'execResponseUserName',
      type: 'slot',
    },
    {
      label: '执行协同人',
      value: 'execCoordinationUserName',
      type: 'slot',
    },
    {
      label: '工作时长(分)',
      value: 'workTime',
      type: 'number',
    },
    {
      label: '允许超时(分)',
      value: 'allowTimeout',
      type: 'number',
    },
    {
      label: '提醒于',
      labelTip: '提醒于任务开始前',
      value: 'remindDuration',
      type: 'slot',
    },
  ],
  rules: {
    planStartDate: [
      { required: true, message: '请选择计划开始时间', trigger: 'change' },
    ],
    patrolRouteName: [
      { required: true, message: '请选择巡检线路', trigger: 'change' },
    ],
    execResponseUserName: [
      { required: true, message: '请选择执行负责人', trigger: 'change' },
    ],
    remindDuration: [
      {
        validator: validateRemind,
        trigger: ['blur', 'change'],
      },
      { required: true, message: '请输入提醒时间', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectPatrolRouteInfo = reactive({
  visible: false,
  excludeQueryList: [],
  query: {
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
})
const execResponseUserInfo = reactive({
  visible: false,
  api: getRrgUserList,
  type: '',
  query: {
    hasAllDept: 1,
  },
  row: {},
})
const execCoordinationUserInfo = reactive({
  visible: false,
  api: getRrgUserList,
  query: {
    hasAllDept: 1,
  },
  type: '',
  checkedRowList: [],
  row: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  dateTimePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
    },
  }
  if (props.id) {
    getDetails()
  }
})

function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function _selectPatrolRoute() {
  //巡检路线
  selectPatrolRouteInfo.visible = true
}
function selectPatrolRouteCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data['patrolRouteId'] = data.id
    formInfo.data['patrolRouteName'] = data.routeName
    formInfo.data['execResponseUser'] = data.routeResponseUser
    formInfo.data['execResponseUserName'] = data.routeResponseUserName
  } else {
    formInfo.data['patrolRouteId'] = ''
    formInfo.data['patrolRouteName'] = ''
    formInfo.data['execResponseUser'] = ''
    formInfo.data['execResponseUserName'] = ''
  }
}
function selectExecResponseUser() {
  //执行负责人
  execResponseUserInfo.visible = true
}
function selectExecResponseUserBack(data) {
  if (data && data.id) {
    formInfo.data['execResponseUser'] = data.id
    formInfo.data['execResponseUserName'] = data.name
  } else {
    formInfo.data['execResponseUser'] = ''
    formInfo.data['execResponseUserName'] = ''
  }
}
function selectExecCoordinationUser() {
  //执行协同人
  execCoordinationUserInfo.visible = true
}
function selectExecCoordinationUserBack(data) {
  if (data && data.length) {
    let ids = data.map((item) => item.id)
    let names = data.map((item) => item.name)
    formInfo.data['execCoordinationUser'] = ids.toString()
    formInfo.data['execCoordinationUserName'] = names.toString()
    execCoordinationUserInfo.checkedRowList = data
  } else {
    formInfo.data['execCoordinationUser'] = ''
    formInfo.data['execCoordinationUserName'] = ''
    execCoordinationUserInfo.checkedRowList = ''
  }
}
function save() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let endDate = formInfo.data.planFinishDate
      let startDate = formInfo.data.planStartDate
      if (endDate) {
        let fmartStartDate = new Date(startDate)
        let fmartEndDate = new Date(endDate)
        if (fmartEndDate.getTime() <= fmartStartDate.getTime()) {
          proxy.$message({
            showClose: true,
            message: '计划结束日期不能大于等于计划开始日期',
            type: 'error',
            duration: 3500,
          })
          return
        }
      }
      let api = props.id ? updateTask : creatTask
      api(formInfo.data).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emit('returnBack')
        }
      })
    }
  })
}
function getUserAllList(ids) {
  let params = {
    idIn: ids,
  }
  getDeptUserAll(params).then((res) => {
    if (res && res.success) {
      execCoordinationUserInfo.checkedRowList = res.data
    }
  })
}
function getDetails() {
  getTaskById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      if (formInfo.data.execCoordinationUser) {
        getUserAllList(formInfo.data.execCoordinationUser)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
